package com.cqyc.imview.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.cqyc.imview.dialog.LoadingDialog
import java.lang.reflect.ParameterizedType


abstract class BaseFragment<T : ViewDataBinding, VM : ViewModel> : Fragment() {
    protected lateinit var mBinding: T
    protected lateinit var mViewModel: VM

    private lateinit var loadingDialog: LoadingDialog

    abstract fun setLayout(): Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(this)[getViewModelClass()]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
//        return super.onCreateView(inflater, container, savedInstanceState)
        val view = inflater.inflate(setLayout(), container, false)
        mBinding = DataBindingUtil.bind(view)!!
        mBinding.lifecycleOwner = this
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        loadingDialog = LoadingDialog(requireContext())
    }

    private fun getViewModelClass(): Class<VM> {
        val type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1]
        return type as Class<VM>
    }

    fun showProgress() {
        loadingDialog.show()
    }

    fun dismissProgress() {
        loadingDialog.dismiss()
    }

}